#not /usr/bin/python
import sys
import os
import subprocess
from subprocess import Popen, PIPE, STDOUT, call

input='lailin.txt'
fin=open(input, 'r')

output='test.mcinfo.txt'
fout=open(output, 'w')

### check AMI 
tmp='tmp'
dict_mcinfo=dict()
for lines in fin.readlines():
  if lines[-1]=='\n': line=lines[:-1]
  else: line=lines
  if len(line)==0: continue
  mcid=line.split('.')[1]
  dataset=line.split('/')[0]
  if not mcid in dict_mcinfo.keys(): dict_mcinfo[mcid]={}
  dict_mcinfo[mcid][dataset]={}
  ## look up AMI
  totEvents=None
  filEff=None
  xsec=None
  out=None
  cmd='ami dataset info '+dataset+' > '+tmp
  #print cmd
  #outstat=subprocess.call(cmd, shell=True)
  p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT)
  p.wait()
  if p:
    try:ftmp=open(tmp, 'r')
    except IOError:
      print 'file not exists: ', tmp
      sys.exit(1)
    for lines in  ftmp.readlines():
      if lines[-1]=='\n': line=lines[:-1]
      else: line=lines
      if len(line)==0: continue
      grep='totalEvents'
      if grep in line: totEvents=line.split()[1]
      grep='approx_GenFiltEff'
      if grep in line: filEff=line.split()[1]
      grep='approx_crossSection'
      if grep in line: xsec=line.split()[1]
    dict_mcinfo[mcid][dataset]['totEvents']=totEvents
    dict_mcinfo[mcid][dataset]['filterEff']=filEff
    dict_mcinfo[mcid][dataset]['xsection']=xsec
    fout.write('%-10s%s  %s %s %s\n' % (mcid, dataset, totEvents, filEff, xsec))
  print dataset

cmd='rm '+tmp
if os.path.isfile(tmp):
  p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT)
print 'Done!'
